export const API_BASE_URL = process.env.REACT_APP_API_URL || 'https://api.interview-ai.com'

export const ROUTES = {
  HOME: '/',
  LOGIN: '/login',
  REGISTER: '/register',
  AGENT_DETAIL: '/agent/:id',
  DASHBOARD: '/dashboard',
  PROFILE: '/profile'
}

export const AGENT_TYPES = {
  COMPUTER_SCIENCE: 'computer_science',
  PRODUCT_MANAGEMENT: 'product_management',
  MARKETING: 'marketing',
  FINANCE: 'finance',
  HR: 'human_resources',
  DATA_SCIENCE: 'data_science'
}

export const INTERVIEW_STATUS = {
  NOT_STARTED: 'not_started',
  IN_PROGRESS: 'in_progress',
  COMPLETED: 'completed',
  PAUSED: 'paused'
}

export const QUESTION_TYPES = {
  ALGORITHM: 'algorithm',
  SYSTEM_DESIGN: 'system_design',
  CODING: 'coding',
  BEHAVIORAL: 'behavioral',
  TECHNICAL: 'technical'
}

export const DIFFICULTY_LEVELS = {
  BEGINNER: 'beginner',
  INTERMEDIATE: 'intermediate',
  ADVANCED: 'advanced',
  EXPERT: 'expert'
}

export const MAJORS = [
  '计算机科学与技术',
  '软件工程',
  '数据科学与大数据技术',
  '人工智能',
  '电子信息工程',
  '市场营销',
  '工商管理',
  '人力资源管理',
  '金融学',
  '会计学',
  '国际经济与贸易',
  '其他'
]

export const GRADUATION_YEARS = Array.from({length: 10}, (_, i) => 2024 + i)

export const STORAGE_KEYS = {
  USER_TOKEN: 'interview_user_token',
  USER_INFO: 'interview_user_info',
  INTERVIEW_HISTORY: 'interview_history',
  PREFERENCES: 'user_preferences'
}

export const MESSAGES = {
  LOGIN_SUCCESS: '登录成功',
  LOGIN_ERROR: '登录失败，请检查用户名和密码',
  REGISTER_SUCCESS: '注册成功',
  REGISTER_ERROR: '注册失败，请稍后重试',
  PASSWORD_MISMATCH: '两次输入的密码不一致',
  NETWORK_ERROR: '网络连接失败，请检查网络设置',
  UNKNOWN_ERROR: '未知错误，请稍后重试'
}

// ========================================

// src/utils/api.js
const API_BASE_URL = process.env.REACT_APP_API_URL || 'https://api.interview-ai.com'

// 通用API请求函数
const apiRequest = async (endpoint, options = {}) => {
  const url = `${API_BASE_URL}${endpoint}`
  const token = localStorage.getItem('interview_user_token')
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` })
    }
  }
  
  const finalOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers
    }
  }
  
  try {
    const response = await fetch(url, finalOptions)
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
    }
    
    return await response.json()
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// 用户认证相关API
export const authAPI = {
  // 用户登录
  login: async (credentials) => {
    return apiRequest('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials)
    })
  },
  
  // 用户注册
  register: async (userData) => {
    return apiRequest('/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    })
  },
  
  // 刷新Token
  refreshToken: async () => {
    return apiRequest('/auth/refresh', {
      method: 'POST'
    })
  },
  
  // 用户登出
  logout: async () => {
    return apiRequest('/auth/logout', {
      method: 'POST'
    })
  }
}

// 智能体相关API
export const agentAPI = {
  // 获取所有智能体
  getAgents: async () => {
    return apiRequest('/agents')
  },
  
  // 获取特定智能体详情
  getAgentById: async (id) => {
    return apiRequest(`/agents/${id}`)
  },
  
  // 获取智能体问题
  getAgentQuestions: async (agentId) => {
    return apiRequest(`/agents/${agentId}/questions`)
  }
}

// 面试相关API
export const interviewAPI = {
  // 开始面试
  startInterview: async (agentId) => {
    return apiRequest('/interviews/start', {
      method: 'POST',
      body: JSON.stringify({ agentId })
    })
  },
  
  // 提交答案
  submitAnswer: async (interviewId, questionId, answer) => {
    return apiRequest(`/interviews/${interviewId}/answers`, {
      method: 'POST',
      body: JSON.stringify({ questionId, answer })
    })
  },
  
  // 获取答案评估
  getEvaluation: async (interviewId, questionId) => {
    return apiRequest(`/interviews/${interviewId}/evaluations/${questionId}`)
  },
  
  // 结束面试
  endInterview: async (interviewId) => {
    return apiRequest(`/interviews/${interviewId}/end`, {
      method: 'POST'
    })
  },
  
  // 获取面试历史
  getInterviewHistory: async () => {
    return apiRequest('/interviews/history')
  },
  
  // 获取面试报告
  getInterviewReport: async (interviewId) => {
    return apiRequest(`/interviews/${interviewId}/report`)
  }
}

// 用户相关API
export const userAPI = {
  // 获取用户信息
  getProfile: async () => {
    return apiRequest('/user/profile')
  },
  
  // 更新用户信息
  updateProfile: async (userData) => {
    return apiRequest('/user/profile', {
      method: 'PUT',
      body: JSON.stringify(userData)
    })
  },
  
  // 上传头像
  uploadAvatar: async (file) => {
    const formData = new FormData()
    formData.append('avatar', file)
    
    return apiRequest('/user/avatar', {
      method: 'POST',
      headers: {}, // 让浏览器自动设置Content-Type
      body: formData
    })
  }
}

// 文件上传API
export const uploadAPI = {
  // 上传音频文件
  uploadAudio: async (file) => {
    const formData = new FormData()
    formData.append('audio', file)
    
    return apiRequest('/upload/audio', {
      method: 'POST',
      headers: {},
      body: formData
    })
  },
  
  // 上传视频文件
  uploadVideo: async (file) => {
    const formData = new FormData()
    formData.append('video', file)
    
    return apiRequest('/upload/video', {
      method: 'POST',
      headers: {},
      body: formData
    })
  }
}

// 统计数据API
export const analyticsAPI = {
  // 获取用户统计数据
  getUserStats: async () => {
    return apiRequest('/analytics/user-stats')
  },
  
  // 获取平台统计数据
  getPlatformStats: async () => {
    return apiRequest('/analytics/platform-stats')
  }
}